package com.easytouch.vm.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Pair;

import com.easytouch.core.Configure;
import com.easytouch.core.DriverThread;
import com.easytouch.core.MonitorThread;
import com.easytouch.core.encryption.Base64;
import com.easytouch.core.listener.OnDoorStateChangedListener;
import com.easytouch.core.utils.Log;
import com.easytouch.core.utils.SimTools;
import com.easytouch.core.utils.SystemTools;
import com.easytouch.vm.AppApplication;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.Locale;

/**
 * Created by gulin on 2017/9/28.
 */

public class TYService extends Service {
    private static final String TY_URL = "https://nscreen.pec.com.cn/index.php/api/vone/";
    private static final String INTERFACE_ORDER_LIST = "orderapi/order_list"; //获取售货机未出货订单列表
    private static final String INTERFACE_ORDER_STATUS = "orderapi/order_status"; //修改订单出货状态
    private static final String INTERFACE_VEND_CONTAINER_STATUS = "vendapi/vend_container_status"; //分货柜状态推送接口
    private static final String INTERFACE_VEND_STATUS = "vendapi/vend_status"; //不分货柜售货机故障推送接口
    private static final String INTERFACE_CHECK_VEND_ONLINE = "vendapi/check_vend_online"; //售货机在线状态保持接口
    private static final String INTERFACE_VEND_DOOR_RECORD = "vendapi/vend_door_record"; //售货机开关门记录接口
    private static final String INTERFACE_VEND_SETTING = "vendapi/vend_setting"; //获取售货机状态
    private static final String INTERFACE_VEND__GET_DATATIME = "vendapi/get_dataTime";//获取服务器时间
    private static final int ORDER_STATUS_NOT_QUERY = 0;
    private static final int ORDER_STATUS_QUERY = 1;
    private static final int ORDER_STATUS_SUCCESS = 2;
    private static final int ORDER_STATUS_FAILED = 3;

    private static Log mLogger; //日志
    private TYThread mTYThread;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if(mTYThread != null)
        {
            return super.onStartCommand(intent, flags, startId);
        }
        mLogger = new Log("TYService1.txt");
        mTYThread = new TYThread();
        DriverThread.getInstance().setOnDoorStateChangedListener(mTYThread);
        mTYThread.start();
        return super.onStartCommand(intent, flags, startId);
    }

    public class TYThread extends Thread implements OnDoorStateChangedListener{

        private String mCharset = "UTF-8";
        private String mContentType = "application/x-www-form-urlencoded";

        private long mLastVendSettingTime = 0;
        private long mLastVendStatusTime = 0;
        private long mLastCheckVendOnline = 0;
        private long mLastVendContainerStatusTime = 0;

//        private String mPrivateKey = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBALFgPdeJhR295RfmtHzwsnw5ao+nR5XF6fwzt0gijnBDcviXIQLklBFbDGY0kaBzgorpkWPfF6y6SizAacBCTcUyGTthCpO6FSTQ2e+J/GU0rWwq5NlNwFusHwcA4Jy5GM2yn278aAuDDI9V7MNSnzcGFscV3J9vwjbq0/4+lHCFAgMBAAECgYApU1f1MKgf/s8yW2DvvxCGmsX2BC5MedkDFnV8S/jNtRlDS8q4JtNMm97urQ7EyETA4pwqHZ8hciG3/Xhl/8yoYqOcipPPKgvkM8FaQ1nIgq0z/T0Ntnj1r1deV1bIfrVE33AjOAVL6rT7lOkDDkqTBSZ3nZJRK39wJrgR6+Q6wQJBANwqNo+LuseXSfKj7UTdNWaFkh6noo77oXqlHN7wcPZfPvjm9UdwZ9d9z0G6FV0NZqW1RbrAQepPnDjLaMRULpUCQQDOPxth2EgXaM84uKYyNYEuAv0qSHbzPBk8EkoORQJ5emgzvkyJYkWpw+1dmzdRZzTTgTsBUDF/M1XVuYE1Re4xAkBF0l1bSMUDZ0dcXABzRnQY/2NHtYIoNkUP0C1HxpkMiUg/R3+iGFPWU1/XSFxeFlHnW4WxpCdDV9wDZv7ixI/BAkBeMyqhhPRgZMmIwaV+9zsaNdlFr7VMoR1xd3UFkXVw4HypbXhto0noIQnQIC2i632QQM0fa25AB8VjiYe/OkJxAkAovPZZzMm6/4jogRlabbnk87joPxLEsZKe5DBvcuiG46pnOoONZk5rrCY7dPO63VYh7lkVyRCXt55mPPO2/kvE";
//        private String mKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCxYD3XiYUdveUX5rR88LJ8OWqPp0eVxen8M7dIIo5wQ3L4lyEC5JQRWwxmNJGgc4KK6ZFj3xesukoswGnAQk3FMhk7YQqTuhUk0NnvifxlNK1sKuTZTcBbrB8HAOCcuRjNsp9u/GgLgwyPVezDUp83BhbHFdyfb8I26tP+PpRwhQIDAQAB";

        private boolean isEncryption = true;

        private LinkedList<Pair<String, String>> mQueue = new LinkedList<Pair<String, String>>(); // 主动指令队列

        private synchronized void appendQueueData(final String pInterface, final String pData)
        {
            mQueue.offer(new Pair<String, String>(pInterface, pData));
        }

        private synchronized Pair<String, String> getQueueData()
        {
            return mQueue.poll();
        }

        private synchronized int getQueueCount()
        {
            return mQueue.size();
        }

        @Override
        public void run() {
            super.run();
            sendServerTime();
            while(true)
            {
                SystemClock.sleep(1000);
//                sendOrderList();TODO 耗流量不使用
//                sendVendContainerStatus();//TODO 耗流量不使用
                sendVendStatus();
                sendVendSetting();
                //sendVendOnline();
                while(getQueueCount() > 0)
                {
                    Pair<String, String> pair = getQueueData();
                    String result = sendPostData(pair.first, pair.second);
                    if(result == null)
                    {
                        continue;
                    }
                    handleCommon(decode(result));
                }
            }
        }

        private void handleCommon(final String pMessage)
        {
            if(pMessage == null)
            {
                return;
            }
            JSONObject object;
            try {
                object = new JSONObject(pMessage);
                int retCode = object.getInt("retCode");
                String retMsg = object.getString("retMsg");
                if(retCode != 0)
                {
                    mLogger.e("retCode:" + retCode + " retMsg:" + retMsg);
                    return;
                }
            }
            catch (JSONException e)
            {
                mLogger.e("ty json error:" + e.toString());
            }
        }

        private void sendServerTime() {
            try {
                String serverData = getServerData(TY_URL + INTERFACE_VEND__GET_DATATIME);
                mLogger.i("获取服务器时间json数据："+serverData);
                if(TextUtils.isEmpty(serverData) || serverData==null){
                    return;
                }
                JSONObject  obj = new JSONObject(serverData);
                String retCode = obj.getString("retCode");
                String retMsg = obj.getString("retMsg");
                JSONObject dataObj= obj.getJSONObject("data");
                String dataTime = dataObj.getString("dataTime");
                mLogger.i("retCode:"+retCode+",retMsg:"+retMsg+",dataTime："+dataTime);
//                String dataTime1=decode(dataTime);
                changeMachTime(dataTime);
            } catch (JSONException e) {
                mLogger.i("e1:"+e.toString());
                e.printStackTrace();
            }catch(NullPointerException e){
                mLogger.i("e2:"+e.toString());
                e.printStackTrace();
            }
        }
        private String getServerData(String url) {
            URL newUrl;
            HttpURLConnection conn = null;
            InputStream in = null;
            StringBuffer sBuffer;
            try {
                newUrl = new URL(url);
                conn = (HttpURLConnection) newUrl.openConnection();
                conn.setDoInput(true);
                conn.setReadTimeout(10000);
                conn.setConnectTimeout(15000);
                conn.setRequestMethod("GET");
                conn.setRequestProperty("Content-Type", mContentType + ";charset=" + mCharset);
                if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    sBuffer = new StringBuffer();
                    byte[] buf = new byte[1024];
                    in = conn.getInputStream();
                    for(int n;(n=in.read(buf))!=-1;){
                        sBuffer.append(new String(buf,0,n,mCharset));
                    }
                    return sBuffer.toString();
                }else{
                    mLogger.e("http error code:" + conn.getResponseCode());
                    return null;
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    if(in!=null){
                        in.close();
                    }
                }catch(IOException e){
                    e.printStackTrace();
                }
                if(conn!=null){
                    conn.disconnect();
                }
            }
            return null;
        }

        private void changeMachTime(final String pMessage)
        {
            mLogger.e("pMessage:" + pMessage);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss", Locale.US);
            try {
                long serverTimeLong = sdf.parse(pMessage).getTime();
                mLogger.e("serverTimeLong:" + serverTimeLong);
                if (Math.abs((new Date()).getTime() - serverTimeLong) > 10000) {
                    mLogger.e("修改了系统时间");
                    SystemTools.setSystemTime(pMessage);
            }
                DriverThread.getInstance().setAvmTime(pMessage);
                mLogger.e("修改了机器时间");
            } catch(Exception e){
                mLogger.e("changeMachTime e:"+e.getMessage());
                e.printStackTrace();
            }
        }

        /**
         * 发送售货机在线状态保持接口
         */
        private void sendVendOnline()
        {
            long currentTime = System.currentTimeMillis();
            if(currentTime - mLastCheckVendOnline < 10 * 60 * 1000) //十分钟请求一次
            {
                return;
            }
            mLastCheckVendOnline = currentTime;
            StringBuffer data = new StringBuffer();
//            data.append("{");
//            data.append("\"vend_id\":\"").append(Configure.getMacNo()).append("\"");
//            data.append("}");
            data.append("vend_id=").append(Configure.getMacNo());
            String result = sendPostData(INTERFACE_CHECK_VEND_ONLINE, data.toString());
            if(result == null)
            {
                return;
            }
            handleVendOnline(decode(result));
        }

        private void handleVendOnline(final String pMessage)
        {
            handleCommon(pMessage);
        }

        private void sendVendSetting()
        {
            long currentTime = System.currentTimeMillis();
            if(currentTime - mLastVendSettingTime < 10 * 60 * 1000) //十分钟请求一次
            {
                return;
            }
            mLastVendSettingTime = currentTime;
            StringBuffer data = new StringBuffer();
            data.append("{");
            data.append("\"vend_id\":\"").append(Configure.getMacNo()).append("\"");
            data.append("}");
//            data.append("vend_id=").append(Configure.getMacNo());
            String result = sendPostData(INTERFACE_VEND_SETTING, data.toString());
            if(result == null)
            {
                return;
            }
            handleVendSetting(decode(result));
        }

        private void handleVendSetting(final String pMessage)
        {
            if(pMessage == null)
            {
                return;
            }
            JSONObject object;
            try {
                object = new JSONObject(pMessage);
                int retCode = object.getInt("retCode");
                String retMsg = object.getString("retMsg");
                if(retCode != 0)
                {
                    mLogger.e("retCode:" + retCode + " retMsg:" + retMsg);
                    return;
                }
                JSONArray data = object.getJSONArray("data");
                if(data == null || data.length() == 0)
                {
                    return;
                }
                for (int i = 0;i < data.length();i++)
                {
                    JSONObject obj = data.getJSONObject(i);
                    String lighting_type = obj.getString("lighting_type"); //照明状态（自动、常闭、常亮） 00:自动,01:常闭,02:常亮
                    String lighting_time = obj.getString("lighting_time"); //开关灯时间 HHMMHHMM
                    String left_status = obj.getString("left_status"); //左室状态（制冷、制热、关闭）00:制冷,01:制热,02:关闭
                    String frefrigetemperature = obj.getString("frefrigetemperature"); //制冷温度 01-25
                    String right_status = obj.getString("right_status"); //右室状态（制冷、制热、关闭）00:制冷,01:制热,02:关闭
                    String fwarmtemperature = obj.getString("fwarmtemperature"); //制热温度 40-63
                    String green_lighting_time = obj.getString("green_lighting_time"); //节能时间 HHMMHHMM
                    String counter_id = obj.getString("counter_id"); //货柜编号
                    int box, cold, hot;
                    try
                    {
                        box = Integer.parseInt(counter_id);
                        cold = Integer.parseInt(frefrigetemperature);
                        hot = Integer.parseInt(fwarmtemperature);
                    }
                    catch (NumberFormatException e)
                    {
                        mLogger.e("ty NumberFormatException:" + e.toString());
                        continue;
                    }
                    DriverThread.getInstance().setAvmStatus(box, 0, lighting_type, lighting_time, left_status, right_status, green_lighting_time, cold, hot);
                }
            }
            catch (JSONException e)
            {
                mLogger.e("ty json error:" + e.toString());
            }
        }

        /**
         * 不分货柜售货机故障推送接口
         */
        private void sendVendStatus()
        {
            String data7d = DriverThread.getInstance().getMachRunInfo();
            if(data7d == null || "".equals(data7d))
            {
                return;
            }
            long currentTime = System.currentTimeMillis();
            if(currentTime - mLastVendStatusTime < 15 * 60 * 1000) //十五分钟请求一次
            {
                return;
            }
            mLastVendStatusTime = currentTime;
            StringBuffer data = new StringBuffer();

            String iccid = SimTools.getICCID(AppApplication.context);
            if(iccid == null || "".equals(iccid))
            {
                iccid = "0";
            }
            data.append("{");
            data.append("\"vend_id\":\"").append(Configure.getMacNo()).append("\",");
            data.append("\"door_status\":\"").append(DriverThread.getInstance().doorState == DriverThread.DOOR_OPEN ? 1 : 2).append("\",");
            data.append("\"firmware_revision\":\"").append("AVM-01-142").append("\",");
            data.append("\"main_revision\":\"").append(Configure.getAvmVersion()).append("\",");
            data.append("\"ficcid\":\"").append(iccid).append("\",");
            data.append("\"left_sensor_error\":\"").append(data7d.substring(13, 14)).append("\",");
            data.append("\"suspend\":\"").append(data7d.substring(7, 8)).append("\",");
            data.append("\"right_sensor_error\":\"").append(data7d.substring(12, 13)).append("\",");
            data.append("\"red_model_error\":\"").append(data7d.substring(9, 10)).append("\",");
            data.append("\"light_sensor\":\"").append(data7d.substring(3, 4)).append("\",");
            data.append("\"long\":\"").append(MonitorThread.mdLongitude).append("\",");
            data.append("\"lat\":\"").append(MonitorThread.mdLatitude).append("\"");
            data.append("}");

//            data.append("vend_id=").append(Configure.getMacNo()).append("&");
//            data.append("door_status=").append(DriverThread.getInstance().doorState == DriverThread.DOOR_OPEN ? 1 : 2).append("&"); //开门状态码(1开门 2关门)
//            data.append("firmware_revision=").append("AVM-01-142").append("&"); //终端软件版本号
//            data.append("main_revision=").append(Configure.getAvmVersion()).append("&"); //主控版本号
//            data.append("ficcid=").append(iccid).append("&"); //FICCID号
//            data.append("left_sensor_error=").append(data7d.substring(13, 14)).append("&"); //左传感器故障(1故障 0正常)
//            data.append("suspend=").append(data7d.substring(7, 8)).append("&"); //暂停营业(1暂停 0营业)
//            data.append("right_sensor_error=").append(data7d.substring(12, 13)).append("&"); //右传感器故障(1故障 0正常)
//            data.append("red_model_error=").append(data7d.substring(9, 10)).append("&"); //红外模块故障(1故障 0正常)
//            data.append("light_sensor=").append(data7d.substring(3, 4)).append("&"); //光传感器是否打开
//            data.append("long=").append(MonitorThread.mdLongitude).append("&"); //经度
//            data.append("lat=").append(MonitorThread.mdLatitude); //纬度
            String result = sendPostData(INTERFACE_VEND_STATUS, data.toString());
            if(result == null)
            {
                return;
            }
            handleCommon(decode(result));

        }

        /**
         * 发送分货柜状态推送接口请求
         */
        private void sendVendContainerStatus()
        {
            for (int i = 1;i <= 11;i++) {
                String data7a = DriverThread.getInstance().getAVMConfigInfo(i);
                if (data7a == null) {
                    continue;
                }
                else
                {
                    break;
                }
            }
            long currentTime = System.currentTimeMillis();
            if(currentTime - mLastVendContainerStatusTime < 15 * 60 * 1000) //15分钟请求一次
            {
                return;
            }
            mLastVendContainerStatusTime = currentTime;
            for (int i = 1;i <= 11;i++) {
                String data7a = DriverThread.getInstance().getAVMConfigInfo(i);
                if(data7a == null)
                {
                    continue;
                }
                StringBuffer data = new StringBuffer();
                data.append("{");
                data.append("\"vend_id\":\"").append(Configure.getMacNo()).append("\",");
                data.append("\"container_id\":\"").append(i).append("\",");
                data.append("\"flightup_time\":\"").append(data7a.substring(10, 14)).append("\",");
                data.append("\"flightdown_time\":\"").append(data7a.substring(14, 18)).append("\",");
                data.append("\"flightstate\":\"").append(data7a.substring(8, 10)).append("\",");
                data.append("\"fleftroomstate\":\"").append(data7a.substring(18, 20)).append("\",");
                data.append("\"frightroomstate\":\"").append(data7a.substring(20, 22)).append("\",");
                data.append("\"fenergyconserv_starttime\":\"").append(data7a.substring(22, 26)).append("\",");
                data.append("\"fenergyconserv_endtime\":\"").append(data7a.substring(26, 30)).append("\",");
                data.append("\"frefrigetemperature\":\"").append(data7a.substring(30, 33)).append("\",");
                data.append("\"flefttemperature\":\"").append(data7a.substring(33, 36)).append("\",");
                data.append("\"fwarmtemperature\":\"").append(data7a.substring(36, 39)).append("\",");
                data.append("\"frighttemperature\":\"").append(data7a.substring(39, 42)).append("\"");
                data.append("}");
//                data.append("vend_id=").append(Configure.getMacNo()).append("&");
//                data.append("container_id=").append(i).append("&"); //货柜id
//                data.append("flightup_time=").append(data7a.substring(10, 14)).append("&"); //开灯时间HHMM
//                data.append("flightdown_time=").append(data7a.substring(14, 18)).append("&"); //关灯时间 HHMM
//                data.append("flightstate=").append(data7a.substring(8, 10)).append("&"); //照明状态：00:自动,01:常闭,02:常亮
//                data.append("fleftroomstate=").append(data7a.substring(18, 20)).append("&"); //左室状态--00:制冷,01:制热,02:关闭
//                data.append("frightroomstate=").append(data7a.substring(20, 22)).append("&"); //右室状态--00:制冷,01:制热,02:关闭
//                data.append("fenergyconserv_starttime=").append(data7a.substring(22, 26)).append("&"); //节能开始时间 HHMM
//                data.append("fenergyconserv_endtime=").append(data7a.substring(26, 30)).append("&"); //节能关闭时间 HHMM
//                data.append("frefrigetemperature=").append(data7a.substring(30, 33)).append("&"); //制冷设定温度
//                data.append("flefttemperature=").append(data7a.substring(33, 36)).append("&"); //左室实际温度
//                data.append("fwarmtemperature=").append(data7a.substring(36, 39)).append("&"); //加热设定温度
//                data.append("frighttemperature=").append(data7a.substring(39, 42)); //右室实际温度

                String result = sendPostData(INTERFACE_VEND_CONTAINER_STATUS, data.toString());
                if (result == null) {
                    return;
                }
                handleCommon(decode(result));
            }
        }

        /**
         * 发送获取售货机未出货订单列表请求
         */
        private void sendOrderList()
        {
            StringBuffer data = new StringBuffer();
            data.append("{");
            data.append("\"vendCode\":\"").append(Configure.getMacNo()).append("\"");
            data.append("}");
//            data.append("vendCode=").append(Configure.getMacNo());
            String result = sendPostData(INTERFACE_ORDER_LIST, data.toString());
            if(result == null)
            {
                return;
            }
            handleOrderList(decode(result));
        }

        private void handleOrderList(final String pMessage)
        {
            if(pMessage == null)
            {
                return;
            }
            JSONObject object;
            try {
                object = new JSONObject(pMessage);
                int retCode = object.getInt("retCode");
                String retMsg = object.getString("retMsg");
                if(retCode != 0)
                {
                    mLogger.e("retCode:" + retCode + " retMsg:" + retMsg);
                    return;
                }
                JSONArray data = object.getJSONArray("data");
                if(data == null || data.length() == 0)
                {
                    return;
                }
                for (int i = 0;i < data.length();i++)
                {
                    JSONObject obj = data.getJSONObject(i);
                    String container = obj.getString("container");
                    String order_no = obj.getString("order_no");
                    String road_code = obj.getString("road_code");
                    outGoods(order_no, container, road_code);
                }
            }
            catch (JSONException e)
            {
                mLogger.e("ty json error:" + e.toString());
            }
        }

        /**
         * 出货
         * @param pOrder 订单号
         * @param pBox 货柜
         * @param pRoad 货道
         */
        private void outGoods(final String pOrder, final String pBox, final String pRoad)
        {
            sendOrderStatus(pOrder, ORDER_STATUS_QUERY);
            SimpleDateFormat sd = new SimpleDateFormat("HHmmss", Locale.US);
            String tradeTrace = sd.format(new Date());

            //转换货柜和货道号
            int box = 0;
            int column = 0;
            try
            {
                box = Integer.parseInt(pBox);
                column = Integer.parseInt(pRoad);
            }
            catch (NumberFormatException e)
            {
                mLogger.e(e.toString());
                sendOrderStatus(pOrder, ORDER_STATUS_FAILED);
                return;
            }

            int price = 100;

            //获取商品信息
            String goodsJson = DriverThread.getInstance().getGoodsInfo(box, column);
            if(goodsJson == null)
            {
                mLogger.e("no goods");
            }
            else {
                //转换为json对象
                JSONObject object;
                try {
                    object = new JSONObject(goodsJson);
                    price = object.getInt("price");
                    int num = object.getInt("num");
                    boolean isBreak = object.getBoolean("isBreak");
                    boolean isHaveStock = false;
                    if (box == 11) {
                        isHaveStock = !isBreak;
                    } else {
                        if (num > 0) {
                            isHaveStock = true;
                        }
                    }
                    if (!isHaveStock) {
                        mLogger.i("no stock");
                    }
                } catch (JSONException e) {
                    mLogger.e("goods json error:" + e.toString());
                }
            }

            boolean result = DriverThread.getInstance().outGoods(box, column, price, DriverThread.OUT_GOODS_ALIPAY, tradeTrace, pOrder);
            if(!result)
            {
                mLogger.e("outGoods result failed");
                sendOrderStatus(pOrder, ORDER_STATUS_FAILED);
                return;
            }
            int step = 0;
            int r = -1;
            try {
                while (step <= 120) {
                    Thread.sleep(500);
                    step++;
                    Pair<Integer, Integer> pair = DriverThread.getInstance().getResult(tradeTrace);
                    if(pair != null)
                    {
                        r = pair.first;
                        break;
                    }
                }
            } catch (InterruptedException e) {
            }
            mLogger.i("outGoods result:" + String.valueOf(r));
            if(r == 0)
            {
                //出货成功
                sendOrderStatus(pOrder, ORDER_STATUS_SUCCESS);
            }
            else
            {
                //出货失败
                sendOrderStatus(pOrder, ORDER_STATUS_FAILED);
            }
        }

        private void sendOrderStatus(final String pOrder, final int status)
        {
            StringBuffer data = new StringBuffer();
            data.append("{");
            data.append("\"orderNo\":\"").append(pOrder).append("\",");
            data.append("\"status\":\"").append(status).append("\"");
            data.append("}");
//            data.append("orderNo=").append(pOrder).append("&");
//            data.append("status=").append(status);
            //加入到发送队列
            appendQueueData(INTERFACE_ORDER_STATUS, data.toString());
        }

        private void handleOrderStatus(final String pMessage)
        {
            if(pMessage == null)
            {
                return;
            }
            JSONObject object;
            try {
                object = new JSONObject(pMessage);
                int retCode = object.getInt("retCode");
                String retMsg = object.getString("retMsg");
                if(retCode != 0)
                {
                    mLogger.e("retCode:" + retCode + " retMsg:" + retMsg);
                    return;
                }
            }
            catch (JSONException e)
            {
                mLogger.e("ty json error:" + e.toString());
            }
        }

        private String decode(final String pData)
        {
            if(!isEncryption)
            {
                mLogger.i("isEncryption:"+pData);
                return pData;
            }
            if(pData == null)
            {
                mLogger.i("pData is null");
                return null;
            }
//            byte[] content = Base64.decode(pData);
//            if(content == null)
//            {
//                return null;
//            }
//            String str = new String(content);
//            try {
//                str = new String(RSAUtils.decryptByPublicKey(content, mKey));
//            } catch (Exception e) {
//                mLogger.e("RSA.decrypt failed:" + e.toString());
//                return null;
//            }
//            mLogger.i("decode data : " + str);
//            return str;
            String str = doDecryption(pData);
            if(str == null)
            {
                mLogger.e("decrypt failed");
            }
            mLogger.i(str);
            return str;
        }

        private String sendPostData(final String pInterface, final String pData)
        {
            URL realurl = null;
            InputStream in = null;
            HttpURLConnection conn = null;
            StringBuffer sBuffer;

            mLogger.i(pInterface + " : " + pData);

            String postData = "req_data=" + pData;
            if(isEncryption)
            {
                //加密
//                try {
//                    byte[] rsaBytes = RSAUtils.encryptByPublicKey(pData.getBytes(), mKey);
//                    mLogger.i(Tools.bytesToHexString(rsaBytes));
//                    //String rsa = new String(rsaBytes, "UTF-8");
//                    String sign = Base64.encode(rsaBytes);
//                    //mLogger.i("rsa:" + rsa);
//                    postData = "req_data=" + sign;
//                    mLogger.i("decode:" + new String(RSAUtils.decryptByPrivateKey(Base64.decode(sign), mPrivateKey)));
//                } catch (Exception e) {
//                    mLogger.i("rsa error : " + e.toString());
//                }
                postData = "req_data=" + doEncryption(pData);
            }
            mLogger.i(postData);

            try {
                realurl = new URL(TY_URL + pInterface);
                conn = (HttpURLConnection) realurl.openConnection();
                conn.setDoInput(true);
                conn.setReadTimeout(10000);
                conn.setConnectTimeout(15000);
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Content-Type", mContentType + ";charset=" + mCharset);
                BufferedOutputStream out = new BufferedOutputStream(conn.getOutputStream());
                byte[] bytes = postData.getBytes(mCharset);
                out.write(bytes, 0, bytes.length);
                out.flush();
                out.close();
                if(conn.getResponseCode() == HttpURLConnection.HTTP_OK)
                {
                    sBuffer = new StringBuffer();
                    byte[] buf = new byte[1024];
                    in = conn.getInputStream();
                    for (int n; (n = in.read(buf)) != -1;)
                    {
                        sBuffer.append(new String(buf, 0, n, mCharset));
                    }
                    return sBuffer.toString();
                }else{
                    mLogger.e("http error code:" + conn.getResponseCode());
                    return null;
                }
            } catch (MalformedURLException e) {
                mLogger.e(e.toString());
            } catch (ProtocolException e) {
                mLogger.e(e.toString());
            } catch (UnsupportedEncodingException e) {
                mLogger.e(e.toString());
            } catch(SocketTimeoutException e){
                mLogger.e(e.toString());
            }catch (UnknownHostException e) {
                mLogger.e(e.toString());
            }catch (IOException e) {
                mLogger.e(e.toString());
            }
            finally
            {
                try
                {
                    if(in != null) in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if(conn != null) conn.disconnect();
            }
            return null;
        }

        private String doEncryption(final String pData)
        {
            final String comment = "shtyzx";
            String data = (pData == null ? "" : pData) + comment;
            String base64 = Base64.encode(data.getBytes());
            //将字符串第一位与倒数第三位兑换，第二位与倒数第四位兑换
            String[] swap = new String[6];
            swap[0] = base64.substring(0, 1); //第一位
            swap[1] = base64.substring(1, 2); //第二位
            swap[2] = base64.substring(2, base64.length() - 4); //第三位到倒数第五位
            swap[3] = base64.substring(base64.length() - 4, base64.length() - 3); //倒数第4位
            swap[4] = base64.substring(base64.length() - 3, base64.length() - 2); //倒数第3位
            swap[5] = base64.substring(base64.length() - 2); //倒数第2位到最后
            String temp = swap[0];
            swap[0] = swap[4];
            swap[4] = temp;
            temp = swap[1];
            swap[1] = swap[3];
            swap[3] = temp;
            String result = "";
            for (String s: swap)
            {
                result += s;
            }
            return result;
        }

        private String doDecryption(final String pData)
        {
            final String comment = "shtyzx";
            String base64 = pData;
            if(pData == null && pData.length() < 4)
            {
                return null;
            }
            //将字符串第一位与倒数第三位兑换，第二位与倒数第四位兑换
            String[] swap = new String[6];
            swap[0] = base64.substring(0, 1); //第一位
            swap[1] = base64.substring(1, 2); //第二位
            swap[2] = base64.substring(2, base64.length() - 4); //第三位到倒数第五位
            swap[3] = base64.substring(base64.length() - 4, base64.length() - 3); //倒数第4位
            swap[4] = base64.substring(base64.length() - 3, base64.length() - 2); //倒数第3位
            swap[5] = base64.substring(base64.length() - 2); //倒数第2位到最后
            String temp = swap[0];
            swap[0] = swap[4];
            swap[4] = temp;
            temp = swap[1];
            swap[1] = swap[3];
            swap[3] = temp;
            String result = "";
            for (String s: swap)
            {
                result += s;
            }
            result = new String(Base64.decode(result));
            if(!result.endsWith(comment))
            {
                return null;
            }
            result = result.substring(0, result.length() - comment.length());
            return result;
        }

        @Override
        public void onDoorStateChanged(boolean isDoorOpen) {
            StringBuffer data = new StringBuffer();
            data.append("{");
            data.append("\"vend_id\":\"").append(Configure.getMacNo()).append("\",");
            data.append("\"door_status\":\"").append(isDoorOpen ? 1 : 2).append("\"");
            data.append("}");
//            data.append("vend_id=").append(Configure.getMacNo()).append("&");
//            data.append("door_status=").append(isDoorOpen ? 1 : 2);
            //加入到发送队列
            appendQueueData(INTERFACE_VEND_DOOR_RECORD, data.toString());
        }
    }
}
